package com.example.secondhandshop.ui.activity;

import static android.app.PendingIntent.getActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.model.ItemModel;
import com.example.secondhandshop.ui.adapter.HomeGoodsAdapter;
import com.example.secondhandshop.ui.adapter.SearchHistoryAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SearchActivity extends AppCompatActivity {
    private RecyclerView recyclerView; // 商品列表
    private HomeGoodsAdapter adapter; // 商品适配器
    private List<Item> itemList; // 商品列表数据
    private ItemModel itemModel; // 商品模型
    private int currentPage = 1; // 当前页数
    private boolean isLoading = false; // 是否正在加载
    private SearchView searchView; // 搜索框
    private List<String> searchHistory = new ArrayList<>(); // 搜索历史
    private RecyclerView historyRecyclerView; // 搜索历史列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search); // 确保布局文件正确

        // 初始化视图
        recyclerView = findViewById(R.id.recyclerView);
        searchView = findViewById(R.id.search_view);
        historyRecyclerView = findViewById(R.id.historyRecyclerView);

        // 初始化数据和适配器
        itemList = new ArrayList<>();
        adapter = new HomeGoodsAdapter(itemList, item -> {
            // 处理点击事件，跳转到商品详细页面
            Intent intent = new Intent(this, ItemDetailActivity.class);
            intent.putExtra("itemId", item.getId());
            startActivity(intent);
        });
        searchView.setIconified(false); // 设置SearchView不折叠
        searchView.setQuery("", false); // 清空搜索框

        // 使用 GridLayoutManager 设置为两列
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        itemModel = new ItemModel();

        // 设置搜索框的监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 当用户提交搜索时
                currentPage = 1; // 重置为第一页
                loadProducts(currentPage, 6, query, null); // 加载搜索结果

                saveSearchQuery(query); // 保存搜索历史
                updateSearchHistory(); // 更新历史记录显示

                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 当搜索文本改变时
                return false; // 不处理文本变化
            }
        });

        // 下拉刷新
        SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            currentPage = 1; // 重置为第一页
            loadProducts(currentPage, 6, searchView.getQuery().toString(), null); // 重新加载商品
            swipeRefreshLayout.setRefreshing(false); // 停止刷新动画
        });

        // 上拉加载更多
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1) && !isLoading) {
                    currentPage++; // 页数加1
                    loadProducts(currentPage, 6, searchView.getQuery().toString(), null); // 加载更多商品
                }
            }
        });

        // 加载搜索历史
        loadSearchHistory();

        // 设置历史记录RecyclerView
        historyRecyclerView.setLayoutManager(new GridLayoutManager(this, 5)); // 设置为三列
        SearchHistoryAdapter historyAdapter = new SearchHistoryAdapter(searchHistory, this::onHistoryItemClick);
        historyRecyclerView.setAdapter(historyAdapter);
        updateSearchHistory(); // 更新历史记录显示
    }

    private void onHistoryItemClick(String query) {
        searchView.setQuery(query, false); // 设置查询
        searchView.setIconified(false); // 展开搜索框
        loadProducts(currentPage, 6, query, null); // 加载选中的历史记录对应的商品
    }

    private void loadProducts(int current, int size, String keyword, String typeId) {
        int userId = 550; // 用户ID为550
        isLoading = true; // 设置为正在加载

        itemModel.getItems(userId, current, size, keyword, typeId, new ItemModel.OnProductsFetchedListener() {
            @Override
            public void onSuccess(List<Item> items) {
                Log.e("SearchActivity", "onSuccess: " + items);
                // 确保在主线程中更新 UI
                runOnUiThread(() -> {
                    if (current == 1) {
                        itemList.clear(); // 清空列表以重新加载
                    }
                    itemList.addAll(items); // 添加新商品
                    adapter.notifyDataSetChanged(); // 刷新适配器
                    isLoading = false; // 设置为不再加载
                });
            }

            @Override
            public void onFailure(String error) {
                // 确保在主线程中更新 UI
                runOnUiThread(() -> {
                    Toast.makeText(SearchActivity.this, "加载失败: " + error, Toast.LENGTH_SHORT).show();
                    isLoading = false; // 设置为不再加载
                });
            }
        });
    }

    private void loadSearchHistory() {
        SharedPreferences preferences = getSharedPreferences("search_history", MODE_PRIVATE);
        Set<String> searchHistorySet = preferences.getStringSet("history", new HashSet<>());
        searchHistory.clear();
        if (searchHistorySet != null) {
            searchHistory.addAll(searchHistorySet);
            // 限制为最近的15条搜索记录
            if (searchHistory.size() > 15) {
                searchHistory = new ArrayList<>(searchHistory.subList(0, 15)); // 重新组合为 List
            }
        }
    }

    private void saveSearchQuery(String query) {
        SharedPreferences preferences = getSharedPreferences("search_history", MODE_PRIVATE);
        Set<String> searchHistorySet = preferences.getStringSet("history", new HashSet<>());

        // 保证查询不为空且未存在于历史记录中
        if (!TextUtils.isEmpty(query) && !searchHistorySet.contains(query)) {
            searchHistorySet.add(query); // 添加新查询

            // 限制为最近的15条搜索记录
            if (searchHistorySet.size() > 15) {
                List<String> historyList = new ArrayList<>(searchHistorySet);
                historyList = historyList.subList(historyList.size() - 15, historyList.size()); // 取最后15条
                searchHistorySet = new HashSet<>(historyList);
            }

            SharedPreferences.Editor editor = preferences.edit();
            editor.putStringSet("history", searchHistorySet);
            editor.apply();
        }
    }

    private void updateSearchHistory() {
        if (searchHistory.isEmpty()) {
            historyRecyclerView.setVisibility(View.GONE); // 隐藏历史记录
        } else {
            historyRecyclerView.setVisibility(View.VISIBLE); // 显示历史记录
        }
    }
}